// 性能优化工具集
// 包含：懒加载、缓存管理、节流防抖、内存监控

(function() {
    
class PerformanceOptimizer {
    constructor() {
        // 图片缓存
        this.imageCache = new Map();
        // 视频缓存
        this.videoCache = new Map();
        // 音频缓存
        this.audioCache = new Map();
        // 预加载队列
        this.preloadQueue = [];
        // 内存使用监控
        this.memoryThreshold = 100 * 1024 * 1024; // 100MB
        // 缓存最大数量
        this.maxCacheSize = 50;
        
        this.init();
    }
    
    init() {
        // 监听内存压力
        if ('memory' in performance) {
            this.monitorMemory();
        }
        
        // 预加载相邻文件
        this.setupPreloader();
    }
    
    // 节流函数
    throttle(func, wait) {
        let timeout;
        let previous = 0;
        
        return function(...args) {
            const now = Date.now();
            const remaining = wait - (now - previous);
            
            if (remaining <= 0 || remaining > wait) {
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
                previous = now;
                func.apply(this, args);
            } else if (!timeout) {
                timeout = setTimeout(() => {
                    previous = Date.now();
                    timeout = null;
                    func.apply(this, args);
                }, remaining);
            }
        };
    }
    
    // 防抖函数
    debounce(func, wait, immediate = false) {
        let timeout;
        
        return function(...args) {
            const later = () => {
                timeout = null;
                if (!immediate) func.apply(this, args);
            };
            
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            
            if (callNow) func.apply(this, args);
        };
    }
    
    // 图片懒加载
    lazyLoadImage(src, callback) {
        // 检查缓存
        if (this.imageCache.has(src)) {
            const cachedImage = this.imageCache.get(src);
            if (cachedImage.complete) {
                callback(null, cachedImage);
                return;
            }
        }
        
        const img = new Image();
        img.onload = () => {
            // 存入缓存
            this.addToCache('image', src, img);
            callback(null, img);
        };
        
        img.onerror = (error) => {
            callback(error, null);
        };
        
        img.src = src;
    }
    
    // 视频预加载
    preloadVideo(src, callback) {
        // 检查缓存
        if (this.videoCache.has(src)) {
            callback(null, this.videoCache.get(src));
            return;
        }
        
        const video = document.createElement('video');
        video.preload = 'metadata';
        
        video.addEventListener('loadedmetadata', () => {
            this.addToCache('video', src, {
                element: video,
                duration: video.duration,
                videoWidth: video.videoWidth,
                videoHeight: video.videoHeight
            });
            callback(null, video);
        });
        
        video.addEventListener('error', (error) => {
            callback(error, null);
        });
        
        video.src = src;
    }
    
    // 音频预加载
    preloadAudio(src, callback) {
        // 检查缓存
        if (this.audioCache.has(src)) {
            callback(null, this.audioCache.get(src));
            return;
        }
        
        const audio = document.createElement('audio');
        audio.preload = 'metadata';
        
        audio.addEventListener('loadedmetadata', () => {
            this.addToCache('audio', src, {
                element: audio,
                duration: audio.duration
            });
            callback(null, audio);
        });
        
        audio.addEventListener('error', (error) => {
            callback(error, null);
        });
        
        audio.src = src;
    }
    
    // 添加到缓存
    addToCache(type, key, value) {
        let cache;
        switch (type) {
            case 'image':
                cache = this.imageCache;
                break;
            case 'video':
                cache = this.videoCache;
                break;
            case 'audio':
                cache = this.audioCache;
                break;
            default:
                return;
        }
        
        // 检查缓存大小，超出限制则清理
        if (cache.size >= this.maxCacheSize) {
            this.cleanCache(cache);
        }
        
        cache.set(key, {
            ...value,
            timestamp: Date.now(),
            accessCount: 1
        });
    }
    
    // 清理缓存 - LRU策略
    cleanCache(cache) {
        const entries = Array.from(cache.entries());
        // 按访问时间和访问次数排序
        entries.sort((a, b) => {
            const aScore = a[1].timestamp + (a[1].accessCount * 10000);
            const bScore = b[1].timestamp + (b[1].accessCount * 10000);
            return aScore - bScore;
        });
        
        // 删除最久未使用的项目
        const toDelete = Math.floor(cache.size * 0.3); // 删除30%
        for (let i = 0; i < toDelete; i++) {
            cache.delete(entries[i][0]);
        }
    }
    
    // 内存监控
    monitorMemory() {
        const checkMemory = () => {
            if (performance.memory && performance.memory.usedJSHeapSize > this.memoryThreshold) {
                console.warn('Memory usage high, clearing caches...');
                this.clearAllCaches();
            }
        };
        
        setInterval(checkMemory, 30000); // 每30秒检查一次
    }
    
    // 清理所有缓存
    clearAllCaches() {
        this.imageCache.clear();
        this.videoCache.clear();
        this.audioCache.clear();
        
        // 强制垃圾回收（如果支持）
        if (window.gc) {
            window.gc();
        }
    }
    
    // 预加载相邻文件
    setupPreloader() {
        this.preloadAdjacent = this.debounce((files, currentIndex) => {
            const toPreload = [];
            
            // 预加载前后各2个文件
            for (let i = Math.max(0, currentIndex - 2); i <= Math.min(files.length - 1, currentIndex + 2); i++) {
                if (i !== currentIndex) {
                    toPreload.push({ file: files[i], index: i });
                }
            }
            
            // 异步预加载
            toPreload.forEach(({ file }) => {
                if (file.type === 1) { // 图片
                    this.lazyLoadImage(file.cover, () => {});
                } else if (file.type === 7) { // 视频
                    this.preloadVideo(file.cover, () => {});
                } else if (file.type === 6) { // 音频
                    this.preloadAudio(file.cover, () => {});
                }
            });
        }, 500);
    }
    
    // 获取缓存统计
    getCacheStats() {
        return {
            images: this.imageCache.size,
            videos: this.videoCache.size,
            audios: this.audioCache.size,
            memory: performance.memory ? {
                used: Math.round(performance.memory.usedJSHeapSize / 1024 / 1024) + 'MB',
                total: Math.round(performance.memory.totalJSHeapSize / 1024 / 1024) + 'MB',
                limit: Math.round(performance.memory.jsHeapSizeLimit / 1024 / 1024) + 'MB'
            } : 'Not available'
        };
    }
    
    // 图片压缩（用于缓存优化）
    compressImage(file, maxWidth = 1920, maxHeight = 1080, quality = 0.8) {
        return new Promise((resolve) => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();
            
            img.onload = () => {
                // 计算新尺寸
                let { width, height } = img;
                
                if (width > maxWidth || height > maxHeight) {
                    const ratio = Math.min(maxWidth / width, maxHeight / height);
                    width *= ratio;
                    height *= ratio;
                }
                
                canvas.width = width;
                canvas.height = height;
                
                // 绘制并压缩
                ctx.drawImage(img, 0, 0, width, height);
                canvas.toBlob(resolve, 'image/jpeg', quality);
            };
            
            img.src = URL.createObjectURL(file);
        });
    }
    
    // 创建虚拟滚动管理器
    createVirtualScroller(containerHeight, itemHeight, items) {
        return {
            containerHeight,
            itemHeight,
            items,
            scrollTop: 0,
            
            // 获取可见范围
            getVisibleRange() {
                const start = Math.floor(this.scrollTop / this.itemHeight);
                const end = Math.min(
                    start + Math.ceil(this.containerHeight / this.itemHeight) + 1,
                    this.items.length
                );
                
                return { start: Math.max(0, start - 1), end };
            },
            
            // 更新滚动位置
            updateScrollTop(scrollTop) {
                this.scrollTop = scrollTop;
            },
            
            // 获取可见项目
            getVisibleItems() {
                const { start, end } = this.getVisibleRange();
                return this.items.slice(start, end).map((item, index) => ({
                    ...item,
                    index: start + index,
                    top: (start + index) * this.itemHeight
                }));
            }
        };
    }
}

// 创建全局实例
window.performanceOptimizer = new PerformanceOptimizer();

// 导出工具函数
window.optimizerUtils = {
    throttle: window.performanceOptimizer.throttle.bind(window.performanceOptimizer),
    debounce: window.performanceOptimizer.debounce.bind(window.performanceOptimizer),
    lazyLoadImage: window.performanceOptimizer.lazyLoadImage.bind(window.performanceOptimizer),
    preloadVideo: window.performanceOptimizer.preloadVideo.bind(window.performanceOptimizer),
    preloadAudio: window.performanceOptimizer.preloadAudio.bind(window.performanceOptimizer),
    getCacheStats: window.performanceOptimizer.getCacheStats.bind(window.performanceOptimizer)
};

})(); // 结束立即执行函数